<?php

namespace app\api\controller;

use app\admin\model\Worktags;
use app\common\controller\Api;
use think\Db;


/**
 * 地址
 */
class Address extends Api
{
    protected $noNeedLogin = [''];
    protected $noNeedRight = '*';
    protected $model = null;
    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Addresses();
    }

    /*
     * 地址列表
     */
    public function address_list()
    {

        $params = $this->request->param();
        $query = $this->model->where('user_id', '=', $this->auth->id);
        if (isset($params['is_default'])) {
            $query->where('is_default', '=', $params['is_default']);
        }

        $list = $query->select();
        $this->success('请求成功', $list);
    }
        /*
         * 添加修改地址
         */
    public function saveAddress()
    {
        Db::startTrans();
        $params = $this->request->param();
        if (empty($params['address']) || empty($params['name']) || empty($params['phone'])) {
            $this->error('缺少必需的参数');
        }
        $addressData = [
            'address' => $params['address'],
            'name' => $params['name'],
            'phone' => $params['phone'],
            'is_default' => $params['is_default'],
            'user_id' =>  $this->auth->id,
            'province_id' => $params['province_id'],
            'city_id' => $params['city_id'],
            'district_id' => $params['district_id'],
        ];

        if (!empty($addressData['is_default'])) {
            $this->model->where('user_id', '=', $this->auth->id)
                ->where('is_default', '=', 1)
                ->update(['is_default' => 0]);
        }
        if (isset($params['id'])) {
            $address = $this->model->find($params['id']);
            if (!$address) {
                $this->error('地址不存在');
                db::rollback();
            }
            $this->model->where('id','=',$params['id'])->update($addressData);
            db::commit();
            $this->success('地址更新成功', []);
        } else {
            $this->model->insert($addressData);
            db::commit();
            $this->success('地址添加成功', []);

        }
    }


    public function address_info()
    {

        $params = $this->request->param();
        $info = $this->model->where('id','=',$params['id'])->find();
        $this->success('请求成功', $info);
    }


    public function del_address()
    {

        $params = $this->request->param();
        $info = $this->model->where('id','=',$params['id'])->delete();
        if($info){
            $this->success('请求成功', $info);
        }else{
            $this->error('删除失败');
        }

    }


}
